<?php

namespace App\Http\Controllers;

use App\Models\Plan;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PlanController extends Controller
{
	/**
	 * Date: 30/03/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(Request $request)
	{
		$range = $request->get('range');
		$date = new \DateTime();
		$start = '';
		$end = '';
		$paginate = $request->get('paginate', 15);

		switch ($range) {
			case 'day':
				$start = date('Y-m-d') . ' 00:00:00';
				$end = date('Y-m-d') . ' 23:59:59';
				break;
			case 'week':
				$start = $date->modify('this week')->format('Y-m-d') . '00:00:00';
				$end = $date->add(\DateInterval::createFromDateString('6 day'))->format('Y-m-d');
				break;
			case 'month':
				$start = date('Y-m-01', strtotime('this month')) . '00:00:00';
				$end = date('Y-m-t', strtotime('-1 month')) . '23:59:59';
				break;
			default:
				$start = $request->get('start') . ' 00:00:00';
				$end = $request->get('end') . ' 23:59:59';
				break;
		}

		$query = Plan::query();
		$result = $query->where('user_id', Auth::id())->whereBetween('start', [$start, $end])->paginate($paginate);
		return $this->success($result);
	}

	/**
	 * Date: 2018/2/28
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function store(Request $request){

        $user = Auth::getUser();

        $data = json_decode($request->getContent(),true);

        if(count($data)){
            // 验证

            // 保存
            foreach ($data as $k => $v){
                $plan = new Plan();

                // 查询周计划是否存在
                $plans = $plan
                    ->where('start',$v['start'])
                    ->where('user_id',$user->id)
                    ->where('shop_id',$v['shop_id'])->first();

                if(count($plans) == 0){
                    $plan->user_id = $user->id;
                    $plan->start = date('Y-m-d',strtotime($v['start'])).' 00:00:03';
                    $plan->shop_id = $v['shop_id'];
                    $plan->status = 0;
                    $plan->save();
                }

            }
        }else{
            return $this->failed("没有数据");
        }

        return $this->success(['上传成功']);
    }


}
